package com.xcm.util;

import com.alibaba.fastjson.JSONObject;
import com.xcm.constant.CookieConstant;
import com.xcm.model.SysAuthority;
import com.xcm.model.SysUser;
import com.xcm.model.vo.SysUserVo;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 当前已登录用户Session工具
 *
 * @author 林强
 * @date 2018-04-12 11:15
 */
public class SessionUtils {
    /**
     * 用户信息
     */
    public static final String SESSION_USER = "_sessionUser";

    /**
     * 用户权限
     */
    public static final String SESSION_USER_PERMISSION = "_sessionUserPermission";

    public static SysUser getSessionUser(HttpServletRequest request) {
        Object user = WebUtils.getSessionAttribute(request, SESSION_USER);
        return user == null ? null : (SysUser) user;
    }

    public static void setSessionUser(HttpServletRequest request, SysUser sessionUser) {
        WebUtils.setSessionAttribute(request, SESSION_USER, sessionUser);
    }

    public static JSONObject getSessionPermission(HttpServletRequest request) {
        Object object = WebUtils.getSessionAttribute(request, SESSION_USER_PERMISSION);
        return object == null ? null : (JSONObject) object;
    }

    public static void setSessionPermission(HttpServletRequest request, JSONObject sessionPermission) {
        WebUtils.setSessionAttribute(request, SESSION_USER_PERMISSION, sessionPermission);
    }

    /**
     * 清除session 和 cookie
     *
     * @param request
     * @param response
     */
    public static void invalidate(HttpServletRequest request, HttpServletResponse response) {
        setSessionUser(request, null);
        setSessionPermission(request, null);
        CookieUtils.removeCookie(response, request, CookieConstant.WHOLE_COOKIE_NAME);
    }
}